package cn.wolfcode.wolf2w.interceptor;

import cn.wolfcode.wolf2w.JsonResult.JsonResult;
import cn.wolfcode.wolf2w.annotation.RequireLogin;
import cn.wolfcode.wolf2w.cache.service.IUserInfoRedisService;
import cn.wolfcode.wolf2w.domain.UserInfo;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/*
 * 用户登录检查
 *
 * */
public class CheckLoginInterceptor implements HandlerInterceptor {
    @Autowired
    private IUserInfoRedisService userInfoRedisService;


    //实现登录拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /*
         * HnadlerMethod 代指动态请求
         * 请求映射方法在springMvc封装对象
         * 1.spring容器启动是会解析所有@RequestMapping标签
         * 2.将解析到的所有请求映射方法相关信息封装成一个HandlerMethod,value值就是HaldlerMethod;
         * */
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        String token = request.getHeader("token");
        UserInfo user = userInfoRedisService.getUserByToken(token);
        //判断当前请求方法上是否有注解@RequireLogin
        HandlerMethod hm=(HandlerMethod) handler;
        if (hm.hasMethodAnnotation(RequireLogin.class)){
            if (user == null) {
                //json数据的中文转码
                response.setContentType("application/json; charset=utf-8");
                //没有登录信息，返回没有登录的信息（JSON）
                response.getWriter().write(JSON.toJSONString(JsonResult.noLogin()));
                return false;
            }
        }
        //如果没有贴标签，放行
        return true;
    }
}
